package com.imay.live.manager;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.imay.base.util.ViewUtil;
import com.imay.live.Constants;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.RoomLiveNormalActivity;
import com.imay.live.activity.discovery.DynamicActivity;
import com.imay.live.activity.discovery.FollowControl;
import com.imay.live.activity.dynamics.CommentActivity;
import com.imay.live.activity.dynamics.ReleaseActivity;
import com.imay.live.adapter.DynamicsLinearAdapter2;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.fragment.dynamics.DynamicsParams;
import com.imay.live.fragment.dynamics.OnTouchHeartListener;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.DymaicsUpdateHelper;
import com.imay.live.helper.RepostHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.model.FeedModel;
import com.imay.live.model.MenuItemModel;
import com.imay.live.model.RoomInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.dialog.ChoiseDialogFragment;
import com.imay.live.view.dialog.ShareDialogFragment;
import com.imay.live.view.recyclerview.WrapContentLinearLayoutManager;
import com.imay.live.R;

import java.util.ArrayList;
import java.util.List;


/**
 * 线性动态控制类
 * Created by chan on 2017/3/25.
 */
public class DynamicsLinearManager2 {
    private RecyclerView mRecyclerView;
    private DynamicsLinearAdapter2 mAdapter;
    private Activity mContext;
    private View mView;

    private int mPlayCurrentPosition;

    private volatile boolean isPlaying = false;
    private volatile boolean mIsVoice = false;

    /**
     * ===================业务弹出框模块===================
     */
    // 用户其他
    private List<MenuItemModel> string1 = new ArrayList<>();
    private final int TAG1 = 1;
    // 个人其他
    private List<MenuItemModel> string2 = new ArrayList<>();
    private final int TAG2 = 2;

    FollowControl followControl;

    private FragmentManager mFragmentManager;
    private PlayerManager playerManager;

    private final int MENU_ACTION_DYNAMICS_SHARE = 201;
    private final int MENU_ACTION_DYNAMICS_DEL = 202;
    private final int MENU_ACTION_DYNAMICS_EDIT = 203;
    private final int MENU_ACTION_DYNAMICS_RECOVERY = 204;
    private final int MENU_ACTION_DYNAMICS_REPORT = 205;

    public static final int TYPE_PROFILE = 0x1;


    public DynamicsLinearManager2(FragmentManager mFragmentManager, final Activity context, RecyclerView recyclerView, View view, OnTouchHeartListener listener, boolean visiableFeed,int openType) {
        mContext = context;
        initData();

        mView = view;

        mRecyclerView = recyclerView;
        WrapContentLinearLayoutManager layoutManager
                = new WrapContentLinearLayoutManager(context);
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new DynamicsLinearAdapter2(context, visiableFeed);
        mAdapter.setTouchHeartListener(listener);
        if (openType!=TYPE_PROFILE) {
            mAdapter.setEmptyView(LayoutInflater.from(context).inflate(R.layout.view_load_layout, null));
        }
        mAdapter.bindToRecyclerView(mRecyclerView);

        mPlayCurrentPosition = -1;

        playerManager = new PlayerManager();
        playerManager.initPlayer(context.getApplication());

        this.mFragmentManager = mFragmentManager;
        initListener();
    }


    /**
     * 初始化数据
     */
    private void initData() {
        string1.clear();
        string2.clear();

        string1.add(new MenuItemModel(MENU_ACTION_DYNAMICS_SHARE, R.string.str_dynamics_share));
        string1.add(new MenuItemModel(MENU_ACTION_DYNAMICS_RECOVERY, R.string.str_dynamics_recovery));
        string1.add(new MenuItemModel(MENU_ACTION_DYNAMICS_REPORT, R.string.str_dynamics_report));

        string2.add(new MenuItemModel(MENU_ACTION_DYNAMICS_SHARE, R.string.str_dynamics_share));
        string2.add(new MenuItemModel(MENU_ACTION_DYNAMICS_DEL, R.string.str_dynamics_del));
        string2.add(new MenuItemModel(MENU_ACTION_DYNAMICS_EDIT, R.string.str_dynamics_edit));
    }

    public DynamicsLinearAdapter2 getmAdapter() {
        return mAdapter;
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        mRecyclerView.addOnScrollListener(scrollListener);

        /**
         * Recycler单击事件，分控件处理
         */
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (!adapter.getData().isEmpty()) {
                    Object itemEntity = adapter.getItem(position);
                    MobclickAgent.onEvent(mContext, "feed_click_content");
                    switch (view.getId()) {
                        case R.id.iv_item_dongtai_content_des_qita: // 其他
                            if (itemEntity instanceof FeedModel) {
                                FeedModel bean = (FeedModel) itemEntity;
                                if (bean.getUid() == AccountManager.getInstance().getUid()) {
                                    ChoiseDialogFragment.show(mFragmentManager, string2, TAG2, new ChoiseItemClick(position));
                                } else {
                                    if (bean.isIsLike()) {
                                        ChoiseDialogFragment.show(mFragmentManager, string1, TAG1, new ChoiseItemClick(position));
                                    } else {
                                        List<MenuItemModel> string = new ArrayList();
                                        string.addAll(string1);
                                        string.remove(1);
                                        ChoiseDialogFragment.show(mFragmentManager, string, TAG1, new ChoiseItemClick(position));
                                    }
                                }
                            }
                            break;
                        case R.id.rl_dynamics_content:
                        case R.id.ll_dynamics_content_live: // 直播间跳转
                            if (itemEntity instanceof RoomInfoModel) {
                                RoomInfoModel bean = (RoomInfoModel) itemEntity;
                                RoomLiveNormalActivity.startActivity(mContext, bean);
                            }
                            break;
                        case R.id.tv_item_content_name:
                        case R.id.civ_item_content_img: // 头像
                            if (itemEntity instanceof FeedModel) {
                                FeedModel bean = (FeedModel) itemEntity;
                                ProfileActivity.start(mContext, bean.getUid());
                            } else if (itemEntity instanceof RoomInfoModel) {
                                RoomInfoModel bean = (RoomInfoModel) itemEntity;
                                ProfileActivity.start(mContext, bean.getUser().getUid());
                            }
                            break;
                        case R.id.tv_item_dongtai_content_des_pinglun_text: // 评论
                        case R.id.iv_item_dongtai_content_des_pinglun: // 评论
                            FeedModel bean = (FeedModel) itemEntity;
                            CommentActivity.startActivity(mContext, bean, position, Constants.DYNAMICS_UPDATE_REQUEST);
                            break;
                        case R.id.tv_dynfllow: // 关注
                            FeedModel beanf = (FeedModel) itemEntity;
                            if (beanf != null) {
                                if (followControl == null) {
                                    followControl = new FollowControl();
                                }
                                UserModel userModel = beanf.getUser();
                                if (userModel == null) {
                                    return;
                                }
                                followControl.followChanged(mContext, beanf.getUser());
                                for (Object o : adapter.getData()) {
                                    if (o instanceof FeedModel) {
                                        FeedModel feedModel = (FeedModel) o;
                                        if (feedModel.getUser() != null && feedModel.getUser().getUid() == userModel.getUid()) {
                                            feedModel.getUser().setMyFollow(userModel.myFollow);
                                        }
                                    }
                                }
                                adapter.notifyDataSetChanged();
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        });
    }

    /**
     * 修改评论数
     *
     * @param position
     * @param countComment
     */
    public void setCountComment(int position, int countComment) {
        if (position != -1) {
            position = position + mAdapter.getHeaderLayoutCount();
            if (mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                View view = layoutManager.findViewByPosition(position);
                if (view != null) {
                    TextView textView = (TextView) view.findViewById(R.id.tv_item_dongtai_content_des_pinglun_text);
                    textView.setText(mContext.getApplicationContext().getString(R.string.str_dynamics_comment_text, countComment));
                }
            }
        }
    }

    /**
     * 弹出框的回调
     */
    public class ChoiseItemClick implements ChoiseDialogFragment.OnItemClickListener {

        private int position;

        public ChoiseItemClick(int position) {
            this.position = position;
        }

        @Override
        public void itemClick(int tagCallBack, int i, MenuItemModel item) {
            switch (tagCallBack) {
                case TAG1: // 用户其他
                    userChoise(i, position, item);
                    break;
                case TAG2: // 个人其他
                    personChoise(i, position, item);
                    break;
            }
        }
    }

    /**
     * 用户其他(他人)
     *
     * @param i
     */
    private void userChoise(final int i, final int position, MenuItemModel item) {
        final FeedModel bean = (FeedModel) mAdapter.getItem(position);
        switch (item.getAction()) {
            case MENU_ACTION_DYNAMICS_SHARE: // 分享
                share(position);
                break;
            case MENU_ACTION_DYNAMICS_RECOVERY: // 回收赞
                likeDel(bean, position);
                break;
            case MENU_ACTION_DYNAMICS_REPORT: // 举报
                if (bean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
                    RepostHelper.getInstance().reportPicture(mFragmentManager, mContext, bean.getFeedId(), bean.getUid(), bean.getImgUrl());
                } else if (bean.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
                    RepostHelper.getInstance().reportVideo(mFragmentManager, mContext, bean.getFeedId(), bean.getUid(), bean.getVideoUrl());
                }
                break;
        }
    }

    /**
     * 分享
     *
     * @param position
     */
    private void share(final int position) {
        FeedModel feed = (FeedModel) mAdapter.getItem(position);
        String imageUrl = null;
        if (feed.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_IMAGE) {
            imageUrl = feed.getImgUrl();
        } else if (feed.getItemType() == DynamicsParams.VIEWTYPE_LINEAR_VIDEO) {
            imageUrl = UrlHelper.getVideoThumbUrl(feed.getVideoUrl());
        }
        final String url = UrlHelper.getShareDynamicsUrl(feed.getFeedId());
        final String contentTitle = mContext.getString(R.string.str_dynamics_share_content_title, feed.getUser().getNick());
        final String contentDes = mContext.getString(R.string.str_dynamics_share_content_des);
        DialogFragmentHelper.showDialogFragment(mFragmentManager, ShareDialogFragment.newInstance(ShareDialogFragment.WEB, url, contentTitle, contentDes, imageUrl, feed));
    }

    /**
     * 个人其他(自己)
     *
     * @param position
     */
    private void personChoise(int i, final int position, MenuItemModel item) {
        final FeedModel bean = (FeedModel) mAdapter.getItem(position);
        switch (item.getAction()) {
            case MENU_ACTION_DYNAMICS_SHARE: // 分享
                share(position);
                break;
            case MENU_ACTION_DYNAMICS_DEL: // 删除动态
                DialogFragmentHelper.showConfirmDialog(mFragmentManager, mContext.getString(R.string.str_dynamics_del_note), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        feedDel(bean.getFeedId(), position);
                    }
                });
                break;
            case MENU_ACTION_DYNAMICS_EDIT: // 编辑动态
                if (bean.getRepostedFeed() != null && bean.getRepostedFeed().getUid() == 0) {
                    ToastUtil.show(mContext, R.string.str_dynamics_share_note);
                } else {
                    ReleaseActivity.startActivity(mContext, null, null, bean, ReleaseActivity.MODIFY, Constants.DYNAMICSFEED_REQUEST_CODE);
                }
                break;
        }
    }

    /**
     * 取消赞
     *
     * @param bean
     */
    protected void likeDel(final FeedModel bean, final int position) {
        ProtoRequestHelper.task(ProtoHttpFactory.likeDel(bean.getFeedId())).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                bean.setCountLike(bean.getCountLike() - 1);
                bean.setIsLike(false);
                // 通知修改
                DymaicsUpdateHelper.modifyLabels(bean);
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                            View view = mRecyclerView.getLayoutManager().findViewByPosition(position + mAdapter.getHeaderLayoutCount());
                            if (view != null) {
                                ImageView imageView = (ImageView) view.findViewById(R.id.iv_item_dongtai_content_des_heart);
                                imageView.setSelected(false);
                                TextView textView = (TextView) view.findViewById(R.id.tv_item_dongtai_content_des_heart_text);
                                textView.setText(mContext.getApplicationContext().getString(R.string.str_dynamics_like_text, bean.getCountLike()));
                            }
                        }
                    }
                });

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(mContext, code);
            }
        });
    }

    /**
     * 删除动态
     *
     * @param feedId
     * @param position1 当前位置
     */
    protected void feedDel(final int feedId, final int position1) {
        ProtoRequestHelper.task(ProtoHttpFactory.feedDel(feedId)).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<JSONObject> result = JSON.parseObject(data, new TypeReference<Result<JSONObject>>() {
                }.getType());
                if (result.result == ResultCode.CodeSuccess) {
                    mAdapter.getData().remove(position1);
                    mAdapter.notifyDataSetChanged();
                    if (mAdapter.getData().isEmpty()) {
                        if (mContext instanceof DynamicActivity) { // 删除回调上一层显示
                            Intent intent = mContext.getIntent();
                            intent.putExtra(Constants.DynamicsUpdate.DYNAMICS_ACTION_KEY, Constants.DynamicsUpdate.ACTION_DYNAMICS_DEL);
                            mContext.setResult(Activity.RESULT_OK, intent);
                            mContext.finish();
                        }
                    }
                    DymaicsUpdateHelper.deleteDynamics(feedId);
                } else {
                    ErrorResult.toastError(mContext, result.result);
                }
            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ErrorResult.toastError(mContext, code);
            }
        });
    }

    /**
     * 播放视频
     *
     * @param position
     * @param mRelativeLayout
     * @param mImageView
     * @param volueImage
     */
    private void play(int position, RelativeLayout mRelativeLayout, final ImageView mImageView, final ImageView volueImage) {
        if (mAdapter.getData().isEmpty()) {
            return;
        }
        int positionWithHead = position;
        if (mAdapter.getHeaderLayoutCount() > 0) {
            positionWithHead = position - 1;
        }
        Object datasBean = mAdapter.getData().get(positionWithHead);
        if (datasBean instanceof FeedModel) {
            FeedModel item = (FeedModel) datasBean;
            if (item.getRepostedFeed() != null && item.getRepostedFeed().getUid() == 0) { // 动态已删除
                return;
            }
            if (TextUtils.isEmpty(item.getVideoUrl())) {
                return;
            }
            playerManager.setTextureParentView(mRelativeLayout);
            final String url = item.getVideoUrl();
            /*int result = playerManager.playTX(url, new ITXLivePlayListener() {
                @Override
                public void onPlayEvent(int event, Bundle bundle) {
                    if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) {
                        if (volueImage != null) {
                            if (volueImage.getTag() instanceof Boolean) {
                                Boolean isVolue = (Boolean) volueImage.getTag();
                                if (isVolue) {
                                    playerManager.setMute(false);
                                    mIsVoice = true;
                                    return;
                                }
                            } else {
                                volueImage.setTag(false);
                            }
                        }
                        playerManager.setMute(true);
                        mIsVoice = false;
                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS) {

                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
                        playerManager.replayer(url);
                    }
                }

                @Override
                public void onNetStatus(Bundle bundle) {

                }
            });*/
            /**
             * 用EXO播放视频
             */
            int result = playerManager.playEXO(url);
            if (volueImage != null) {
                if (volueImage.getTag() instanceof Boolean) {
                    Boolean isVolue = (Boolean) volueImage.getTag();
                    if (isVolue) {
                        playerManager.setMute(false);
                        mIsVoice = true;
                    } else {
                        playerManager.setMute(true);
                        mIsVoice = false;
                    }
                } else {
                    volueImage.setTag(false);
                    playerManager.setMute(true);
                    mIsVoice = false;
                }
            }


            if (result == 0) {
                isPlaying = true;
                mPlayCurrentPosition = position;
            }
        }
    }

    /**
     * 停止播放
     *
     * @param recyclerView
     */
    private void stopPlay(RecyclerView recyclerView) {
        if (recyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            View mChild = linearLayoutManager.findViewByPosition(mPlayCurrentPosition);
            if (mChild != null) {
                final RelativeLayout mRelativeLayout =
                        $(R.id.rl_dynamics_content, mChild);
                if (mRelativeLayout != null) {
                    final ImageView mImageView
                            = $(R.id.iv_item_content_img, mRelativeLayout);
                    ImageView volueImage = $(R.id.iv_item_content_video_voice, mRelativeLayout);
                    ViewTreeObserver vto2 = mRelativeLayout.getViewTreeObserver();
                    vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            mRelativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                    });
                    int[] loc = ViewUtil.getLocation(mRelativeLayout);
                    int h = mRelativeLayout.getHeight() + loc[1];
                    if ((h < (ViewUtil.mScreemHeight / 4)) || (loc[1] > (ViewUtil.mScreemHeight / 3) * 2)) {
                        mIsVoice = false;
                        mPlayCurrentPosition = -1;
                        isPlaying = false;
                        playerManager.stop();
                        if (volueImage == null) {
                            return;
                        }
                        volueImage.setTag(false);
                        volueImage.setSelected(false);
                        mImageView.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                mIsVoice = false;
                mPlayCurrentPosition = -1;
                isPlaying = false;
                playerManager.stop();
            }
        }
    }


    /**
     * 刷新data
     *
     * @param list
     */
    public void setNewData(List<Object> list) {
        if (mAdapter == null) {
            return;
        }
        mAdapter.setNewData(list);
    }

    /**
     * 清空adapter的数据
     */
    public void notifyItemMoved() {
        if (mAdapter == null) {
            return;
        }
        mAdapter.notifyItemMoved(0, mAdapter.getData().size());
    }


    /**
     * 增加datas
     *
     * @param list
     */
    public void addDatas(List<Object> list) {
        if (mAdapter == null) {
            return;
        }
        mAdapter.addData(list);
    }

    /**
     * 增加datas
     *
     * @param list
     */
    public void addDatas(int position, List<Object> list) {
        if (mAdapter == null) {
            return;
        }
        mAdapter.addData(position, list);
    }

    /**
     * 播放第几个
     *
     * @param position
     */
    public void play(int position) {
        if (mRecyclerView == null) {
            return;
        }
        BaseViewHolder viewHolder = (BaseViewHolder) mRecyclerView.findViewHolderForLayoutPosition(position);
        if (viewHolder == null) {
            return;
        }
        RelativeLayout mRelativeLayout1 = viewHolder.getView(R.id.rl_dynamics_content);
        if (mRelativeLayout1 != null) {
            ImageView mImageView1 = viewHolder.getView(R.id.iv_item_content_img);
            ImageView volueImage1 = viewHolder.getView(R.id.iv_item_content_video_voice);
            play(position, mRelativeLayout1, mImageView1, volueImage1);
        }
    }

    /**
     * 停止播放
     */
    public int stop() {
        if (isPlaying) {
            final int position = mPlayCurrentPosition;
            playerManager.stop();
            if (mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
                View mChild = linearLayoutManager.findViewByPosition(mPlayCurrentPosition);
                if (mChild != null) {
                    final RelativeLayout mRelativeLayout =
                            $(R.id.rl_dynamics_content, mChild);
                    if (mRelativeLayout != null) {
                        final ImageView mImageView
                                = $(R.id.iv_item_content_img, mRelativeLayout);
                        ImageView volueImage = $(R.id.iv_item_content_video_voice, mRelativeLayout);
                        isPlaying = false;
                        mIsVoice = false;
                        mPlayCurrentPosition = -1;
                        if (volueImage == null) {
                            return -1;
                        }
                        volueImage.setTag(false);
                        volueImage.setSelected(false);
                        mImageView.setVisibility(View.VISIBLE);
                    }
                }
                return position;
            }
            return position;
        }
        return -1;
    }

    /**
     * 滑动监听事件
     */
    private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                if (!isPlaying) {
                    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    final int position1 = linearLayoutManager.findFirstVisibleItemPosition();
                    final int position2 = linearLayoutManager.findLastVisibleItemPosition();
                    if (position2 - position1 == 1) {
                        View mChild1 = linearLayoutManager.findViewByPosition(position1);
                        if (mChild1 != null) {
                            final RelativeLayout mRelativeLayout1 = $(R.id.rl_dynamics_content, mChild1);
                            final ImageView mImageView1 = $(R.id.iv_item_content_img, mChild1);
                            final ImageView volueImage1 = $(R.id.iv_item_content_video_voice, mChild1);
                            if (mRelativeLayout1 != null) {
                                mImageView1.setVisibility(View.VISIBLE);
                                int[] loc = ViewUtil.getLocation(mRelativeLayout1);
                                ViewTreeObserver vto2 = mRelativeLayout1.getViewTreeObserver();
                                vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                    @Override
                                    public void onGlobalLayout() {
                                        mRelativeLayout1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                    }
                                });
                                int h = mRelativeLayout1.getHeight() + loc[1];
                                if (h > (ViewUtil.mScreemHeight / 2)) {
                                    play(position1, mRelativeLayout1, mImageView1, volueImage1);
                                    return;
                                }
                            }
                        }

                        View mChild2 = linearLayoutManager.findViewByPosition(position2);
                        if (mChild2 != null) {
                            final RelativeLayout mRelativeLayout2 =
                                    $(R.id.rl_dynamics_content, mChild2);
                            final ImageView mImageView2 = $(R.id.iv_item_content_img, mChild2);
                            final ImageView volueImage2 = $(R.id.iv_item_content_video_voice, mChild2);
                            if (mRelativeLayout2 != null) {
                                mImageView2.setVisibility(View.VISIBLE);
                                int[] loc = ViewUtil.getLocation(mRelativeLayout2);
                                if (loc[1] < (ViewUtil.mScreemHeight / 2)) {
                                    play(position2, mRelativeLayout2, mImageView2, volueImage2);
                                }
                            }
                        }
                    } else if (position2 - position1 > 1) {
                        final int position3 = position1 + 1;
                        View mChild3 = linearLayoutManager.findViewByPosition(position3);
                        if (mChild3 != null) {
                            final RelativeLayout mRelativeLayout = $(R.id.rl_dynamics_content, mChild3);
                            final ImageView mImageView = $(R.id.iv_item_content_img, mChild3);
                            final ImageView volueImage = $(R.id.iv_item_content_video_voice, mChild3);
                            if (mRelativeLayout != null) {
                                mImageView.setVisibility(View.VISIBLE);
                                int[] loc = ViewUtil.getLocation(mRelativeLayout);
                                if (loc[1] < (ViewUtil.mScreemHeight / 2)) {
                                    play(position3, mRelativeLayout, mImageView, volueImage);
                                }
                            }
                        }
                    } else if (position1 == 0) {
                        View mChild1 = linearLayoutManager.findViewByPosition(position1);
                        if (mChild1 != null) {
                            final RelativeLayout mRelativeLayout1 = $(R.id.rl_dynamics_content, mChild1);
                            final ImageView mImageView1 = $(R.id.iv_item_content_img, mChild1);
                            final ImageView volueImage1 = $(R.id.iv_item_content_video_voice, mChild1);
                            if (mRelativeLayout1 != null) {
                                mImageView1.setVisibility(View.VISIBLE);
                                int[] loc = ViewUtil.getLocation(mRelativeLayout1);
                                ViewTreeObserver vto2 = mRelativeLayout1.getViewTreeObserver();
                                vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                                    @Override
                                    public void onGlobalLayout() {
                                        mRelativeLayout1.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                                    }
                                });
                                int h = mRelativeLayout1.getHeight() + loc[1];
                                if (h > (ViewUtil.mScreemHeight / 2)) {
                                    play(position1, mRelativeLayout1, mImageView1, volueImage1);
                                    return;
                                }
                            }
                        }
                    }
                } else {
                    stopPlay(recyclerView);
                }
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (isPlaying && mPlayCurrentPosition != -1) {
                stopPlay(recyclerView);
            }
        }
    };

    /**
     * 查找控件
     *
     * @param id
     * @return
     */
    protected <T extends View> T $(int id) {
        return (T) mView.findViewById(id);
    }

    protected <T extends View> T $(int id, View view) {
        return (T) view.findViewById(id);
    }

    /**
     * 调节声音
     */
    public void setVoice(int position) {
        LinearLayoutManager linearLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
        View view = linearLayoutManager.findViewByPosition(position);
        if (view != null) {
            ImageView mIvVoice = $(R.id.iv_item_content_video_voice, view);
            if (mIvVoice != null) {
                mIvVoice.setTag(!mIsVoice);
                mIvVoice.setSelected(!mIsVoice);
            }
        }
        if (!mIsVoice) {
            playerManager.setMute(false);
            mIsVoice = true;
        } else {
            playerManager.setMute(true);
            mIsVoice = false;
        }
    }

    public void onPauce() {
        playerManager.pause();
    }

    public void onResume() {
        playerManager.resume();
    }

    public void release() {
        playerManager.release();
        mAdapter = null;
        mRecyclerView = null;
        Runtime.getRuntime().gc();
    }
}
